package own.stu.jobgib.playown.io.fileRead;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class HandleMaxRepeatProblem_v1 extends HandleMaxRepeatProblem_v0 {

    private static ExecutorService executorService = Executors.newFixedThreadPool(6);

    public static void main(String[] args) throws Exception {
        HandleMaxRepeatProblem_v1 v1 = new HandleMaxRepeatProblem_v1();
        v1.readData(Constant.FILE_NAME);
        executorService.shutdown();
    }

    @Override
    public void readData(String fileName) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "utf-8"));
        String line;

        int count = 1;
        Stopwatch stopwatch = Stopwatch.createStarted();
        AtomicInteger cnt = new AtomicInteger();
        while ((line = reader.readLine()) != null) {
            if (count % 100 == 0) {
                log.info("读取100行,总耗时间: {}", stopwatch.toString());// System.gc();
                String finalLine = line;
                cnt.incrementAndGet();
                executorService.submit(() -> {
                    Constant.SplitData.splitLine(finalLine, countMap);
                    cnt.decrementAndGet();
                });
            }
            count++;
        }
        stopwatch.stop();
        while(cnt.get() != 0){
            TimeUnit.MILLISECONDS.sleep(50);
        }
        findMostAge();
        log.info("end: {}", stopwatch.toString());

    }
}
